import type { AxiosInstance, AxiosResponse } from 'axios';

// 需要使用mock的url
const { VITE_USE_MOCK_URL } = import.meta.env;
const mockUrls = VITE_USE_MOCK_URL?.split(',') || [];

// 导入所有mock数据
const modules = import.meta.glob('./*.ts', { eager: true });
const mockList: Mock[] = [];

Object.keys(modules).forEach((key) => {
  if (key !== './index.ts') {
    const mock: Mock[] = (modules[key] as any).default;
    mockList.push(...mock);
  }
});

// mock拦截器
const mockResponse = (response: AxiosResponse) => {
  const url = response.config.url;
  const method = response.config.method;
  if (mockUrls.length > 0 && !mockUrls.includes(url)) {
    return response;
  } else {
    const mock = mockList.find((item) => item.url === url && (item.method === method || item.method === 'POST'));
    return mock?.response();
  }
};

// 使用mock
const mock = (request: AxiosInstance) => {
  request.interceptors.response.use((response) => mockResponse(response), (response) => mockResponse(response));
};

// 导出mock
export default mock;
